import React, { ReactHTMLElement } from 'react';

import Image from "next/image";
import { Button, Col, Dropdown, FloatButton, Input, Layout, Menu, MenuProps, message, Popconfirm, Popover, Row, Space, theme, Tooltip } from 'antd';
import {
  ArrowUpOutlined,
  AudioMutedOutlined,
  AudioOutlined,
  AudioTwoTone,
  DatabaseOutlined,
  DeleteOutlined,
  EditOutlined,
  LogoutOutlined,
  MessageOutlined,
  PlusOutlined,
  ProfileOutlined,
  SettingOutlined,
  SolutionOutlined,
  UnorderedListOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { useState, useEffect, useRef, useCallback, useMemo } from "react";
import ContentMsg from "../contentmsg";
import ContentInfo from "../contentinfo";
import { Footer } from "antd/es/layout/layout";
import ShowDialog from "../showDialog";
import { deleteAxios, get, isLoggedIn, post, putAxios } from '../../service/axiosManager';
import CueWordManage from "../maintenance/CueWordManage";
import '../css/page.css';
import { set } from "lodash";
import DataSetView from "../dataset/KnowledgeBase";
import { ApplicationData, SessionItem } from '@/service/request/modal/dataModal';
import { getChatSession, getMcpConfigs } from '@/service/request/requestApi';
import { ResponseMCPConfig, ResponseModal } from '@/service/request/modal/responseModal';
import { AnyARecord } from 'node:dns';
import { ISAV1Svg, LoadingSvg, MaintenanceSvg } from '../assets/CustomizeSvg';
import { QaType } from '@/service/general/enumType';
import { UtilHelpers } from '@/service/general/utils/utilHelpers';

const { Header, Sider, Content } = Layout;

export default function MessageMain({appInfo}: {appInfo?: ApplicationData}) {

    const [collapsed, setCollapsed] = useState(false);
    const {
      token: { colorBgContainer, borderRadiusLG },
    } = theme.useToken();
    const [dialogOpen, setDialogOpen] = useState(false);
    const [openPopover, setOpenPopover] = useState(false);
    const [openPopoverTips, setOpenPopoverTips] = useState(false);
    const [showDataset, setShowDataset] = useState(false);
    // const [inputValue, setInputValue] = useState('');
    const [loggedIn, setLoggedIn] = useState(false);
  
    const [msgList, setMsgList] = useState<any>([]);
  
    const [messageApi, contextHolder] = message.useMessage();
  
    const [msgContent, setMsgContent] = useState<any[]>([]);
    const [contentType, setContentType] = useState('info');
  
    const [lastContentId, setLastContentId] = useState('');
    const [msgId, setMsgId] = useState('');
  
    const [isTyping, setIsTyping] = useState(false);
  
    const [wordTips, setWordTips] = useState([]);
    const [mcpConfigs, setMcpConfigs] = useState<ResponseMCPConfig[]>([]);
  
    const inputRef = useRef<any>(null);
    const qaTextArea = useRef<HTMLTextAreaElement>(null);
  
    // 在 Home 函数组件中添加一个新的状态 inputValue 来管理输入框的值
    const [inputValue, setInputValue] = useState('');
  
    const [selectedKey, setSelectedKey] = useState<string>(''); // 添加新的状态
  
    const [firmName,setFirmName] = useState<string>('');
  
    const [cueWordMaintenance, setCueWordMaintenance] = useState<boolean>(false);
  
    // const [inputType, setInputType] = useState<React.ReactNode>(null);
    // const [inputArea, setInputArea] = useState<React.ReactNode>(null);
  
    // 录音
    const [isRecording,setIsRecording] = useState(false);
    const [isUpAudio, setIsUpAudio] = useState(false);
    const [openMCP, setOpenMCP] = useState<boolean>(false);
    const [qaType, setQaType] = useState<QaType>(QaType.WORDTIPS);
    const mediaStreamRef = useRef<MediaStream | null>(null);
    const mediaRecorderRef = useRef<MediaRecorder | null>(null);
    const audioChunksRef = useRef<Blob[]>([]);
    const contentMsgRef = useRef<any>(null);

    useEffect(() => {
      if (appInfo && appInfo.id && isLoggedIn()) {
        loadSessionData();
      }
    }, [appInfo]);

    useEffect(() => {
      // setInputType(<MessageOutlined />);
      // setInputArea(inputText);
      // if (!login) {
      //   // 如果未登录，执行相应的操作，比如重定向到登录页面
      //   console.log('用户未登录');
      //   // 如果未登录，弹出登录框
      //   setLoggedIn(true);
      //   return;
      // }
      console.log('用户登录了');
      if(isLoggedIn()) {
        // loadData();
        loadWordTips();
        loadMcpConfigs();
      }
    }, []);

    useEffect(() => {
      if (qaTextArea.current) {
        // qaTextArea.current.style.height = "16px";
          qaTextArea.current.style.height = "auto";
          qaTextArea.current.style.height = qaTextArea.current.scrollHeight + "px";
      }
    }, [inputValue]);

    const loadSessionData = () => {
      if (!appInfo) return;
      console.log("appInfo param: \n", appInfo);
      const param = {
        id: appInfo.id
      }
      getChatSession(param).then((res: ResponseModal<SessionItem>) => {
        if (res.code === 0 && res.success) {
          const item = res.result || [];
          if (item.length > 0) {
            loadData(item);
          } else {
            createMsg("新建对话", (id: string) => {
              setMsgId(id);
              setSelectedKey(id.toString()); // 确保转换为字符串
              loadMsg(id, (content: any[]) => {});
            });
          }
          
        }
      }).catch((err) => {
        console.log("获取应用会话失败");
      });
    }
  
    const handleMsgClick = useCallback((e: any) => {
      console.log('点击', e);
      UtilHelpers.CleanTimeout("Process-msg");
      switchSession(e.key);
    }, []);

    const switchSession = (key: any) => {
      setSelectedKey(key);
      setLastContentId('');
      setMsgId((prevMsgId) => {
        if (prevMsgId !== key) {
          setIsTyping(false);
          loadMsg(key, (content: any[]) => {});
        }
        return key;
      });
      loadMsg(key, (content: any[]) => {});
    }
  
    const hidePopover = () => {
      setOpenPopover(false);
    };
    const handleOpenChange = (newOpen: boolean) => {
      setOpenPopover(newOpen);
    };

    const loadData = (sessions: SessionItem[]) => {
      sessions.sort((a: any, b: any) => b.id - a.id);
      const msgList = sessions.map((item: any) => {
        return {
          key: item.id.toString(), // 确保 key 是字符串类型
          style: {
            paddingLeft: 10,
          },
          // icon: <UserOutlined />,
          label: (<>
            <span style={{
              maxWidth: 120,
              fontSize: '16px',
              whiteSpace: 'nowrap', // 防止换行
              overflow: 'hidden', // 隐藏超出部分
              textOverflow: 'ellipsis', // 显示省略号
            }}><ProfileOutlined style={{ marginRight: 10, }} />{item.title}</span>
          </>),
          extra: (<>
            <span className="cursor-pointer mr-3">
              <Popconfirm
                title={<>
                  <Input
                    placeholder="请输入修改后的标题"
                    defaultValue={item.title} // 使用 defaultValue 初始化输入框
                    ref={inputRef} // 使用 ref 获取输入框的值
                  />
                </>}
                onConfirm={() => {
                  const currentTitle = inputRef.current?.input.value || item.title; // 使用 ref 获取最新值
                  console.log('确认编辑', currentTitle);
                  updateMsgTitle(item.id, currentTitle);
                }}
                onCancel={() => {
                  console.log('取消编辑', item);
                }}
                okText="修改"
                cancelText="取消"
              >
                <span className="text-gray-500 text-sm">
                  <EditOutlined />
                </span>
              </Popconfirm>
            </span>
            <Popconfirm
              title={`确定删除对话"${item.title}"吗？`}
              onConfirm={() => {
                console.log('删除', item);
                deleteMsg(item.id);
              }}
              onCancel={() => {
                console.log('取消删除', item);
              }}
              okText="Yes"
              cancelText="No"
            >
              <span className="text-red-500 text-sm">
                <DeleteOutlined />
              </span>
            </Popconfirm>
          </>),
        }
      })
      setMsgList(msgList);
      switchSession(msgList[0].key);
    }
  
    // const loadData = () => {
    //   console.log('加载数据');
    //   get('/ai/chat/session').then((res: any) => {
    //     console.log('加载数据成功', res);
    //     res.result.sort((a: any, b: any) => b.id - a.id);
    //     const msgList = res.result.map((item: any) => {
    //       return {
    //         key: item.id.toString(), // 确保 key 是字符串类型
    //         style: {
    //           paddingLeft: 10,
    //         },
    //         // icon: <UserOutlined />,
    //         label: (<>
    //           <span style={{
    //             maxWidth: 120,
    //             fontSize: '16px',
    //             whiteSpace: 'nowrap', // 防止换行
    //             overflow: 'hidden', // 隐藏超出部分
    //             textOverflow: 'ellipsis', // 显示省略号
    //           }}><ProfileOutlined style={{ marginRight: 10, }} />{item.title}</span>
    //         </>),
    //         extra: (<>
    //           <span className="cursor-pointer mr-3">
    //             <Popconfirm
    //               title={<>
    //                 <Input
    //                   placeholder="请输入修改后的标题"
    //                   defaultValue={item.title} // 使用 defaultValue 初始化输入框
    //                   ref={inputRef} // 使用 ref 获取输入框的值
    //                 />
    //               </>}
    //               onConfirm={() => {
    //                 const currentTitle = inputRef.current?.input.value || item.title; // 使用 ref 获取最新值
    //                 console.log('确认编辑', currentTitle);
    //                 updateMsgTitle(item.id, currentTitle);
    //               }}
    //               onCancel={() => {
    //                 console.log('取消编辑', item);
    //               }}
    //               okText="修改"
    //               cancelText="取消"
    //             >
    //               <span className="text-gray-500 text-sm">
    //                 <EditOutlined />
    //               </span>
    //             </Popconfirm>
    //           </span>
    //           <Popconfirm
    //             title={`确定删除对话"${item.title}"吗？`}
    //             onConfirm={() => {
    //               console.log('删除', item);
    //               deleteMsg(item.id);
    //             }}
    //             onCancel={() => {
    //               console.log('取消删除', item);
    //             }}
    //             okText="Yes"
    //             cancelText="No"
    //           >
    //             <span className="text-red-500 text-sm">
    //               <DeleteOutlined />
    //             </span>
    //           </Popconfirm>
    //         </>),
    //       }
    //     })
    //     setMsgList(msgList);
    //   }).catch((err: any) => {
    //     console.log('加载数据失败', err);
    //   });
    // }
  
    const updateMsgTitle = (id: string, title: string) => {
      console.log('修改标题', id, title);
      putAxios('/ai/chat/session', {
        id: id,
        "appId": appInfo?.id,
        'title': title,
      }).then((res: any) => {
        console.log('修改标题成功', res);
        message.success('修改成功');
        loadSessionData();
      }).catch((err: any) => {
        console.log('修改标题失败', err);
        message.error('修改失败');
      });
    }
  
    const deleteMsg = (id: string) => {
      console.log('删除', id);
      deleteAxios('/ai/chat/session/' + id).then((res: any) => {
        console.log('删除成功', res);
        messageApi.open({
          type: 'success',
          content: '删除成功',
        });
        loadSessionData();
      }).catch((err: any) => {
        console.log('删除失败', err);
        messageApi.open({
          type: 'error',
          content: '删除失败',
        });
      });
    }
  
    const createMsg = (msg: string, callback: (id: string) => void) => {
      console.log("send msg: \n", appInfo);
      post('/ai/chat/session', {
        "appId": appInfo?.id,
        'title': msg,
      }).then((res: any) => {
        console.log('加载数据成功', res);
        loadSessionData();
        callback(res.result.id);
      }).catch((err: any) => {
        console.log('加载数据失败', err);
      });
    }
  
    const sendMsg = (msg: string, sessionId?: string) => {
      const sendMsgId = sessionId || msgId || '';
      if (sendMsgId == '') {
        createMsg(msg, (id: string) => {
          setMsgId(id);
          setSelectedKey(id.toString()); // 确保转换为字符串
          loadMsg(id, (content: any[]) => {
            console.log("send id: " + id);
            sendMsgToServer(msg, id);
          });
        });
      } else {
        sendMsgToServer(msg, sendMsgId);
      }
    }
    const sendMsgToServer = (msg: string, mid: string) => {
      if (isTyping) {
        console.log('正在打字，无法发送消息');
        return;
      }
      setIsTyping(true); // 开始打字机效果
      setLastContentId('');
  
      setMsgContent(prevContent => [...prevContent, {
        key: '-1000',
        question: msg,
        align: 'right',
      }]);
      setInputValue('');
      setTimeout(() => {
        if (contentMsgRef.current) {
          contentMsgRef.current.scrollTop = contentMsgRef.current.scrollHeight;
        }
      },100);
      console.log("send msgId: " + mid);
      post('/ai/chat/qa', {
        'question': msg,
        'refConversationId': mid,
        'isMcp': openMCP,
      }).then((res: any) => {
        console.log('发送消息成功', res);
        if (res.result) {
          const result = res.result;
          result.isReply = true;
          setLastContentId(result.id);
          // 使用函数式更新来避免不必要的重复调用
          setMsgContent((prevMsgContent) => {
            // 检查是否需要更新，避免不必要的状更新
            if (!prevMsgContent.some(item => item.id === result.id)) {
              return prevMsgContent.filter(item => item.key !== '-1000').concat(result);
            }
            return prevMsgContent;
          });
        }
      }).catch((err: any) => {
        setIsTyping(false); // 结束打字机效果
        console.log('发送消息失败', err);
      });
    }
  
  
    const loadMsg = (pid: string, callback: (content: any[]) => void) => {
      get('/ai/chat/qa/list/' + pid).then((res: any) => {
        console.log('加载消息成功', res);
        // 在 setMsgContent 前清理旧的消息内容，以减少内存占用
        setMsgContent(prevContent => {
          // 可以在这里添加逻辑来决定是否需要清理旧数据
          // 例如，如果消息内容非常大，可以选择清空或者只保留分必要数据
          // console.log("msgContent: " + JSON.stringify(msgContent));
          setContentType('msg');
          return res.result;
        });
        callback(res.result);
      }).catch((err: any) => {
        console.log('加载消息失败', err);
      });
    }
  
    const loadWordTips = () => {
      get("/cue/word/all").then((res: any) => {
        console.log('加载提示词成功', res);
        console.log("msgId: \n", msgId);
        const wordTips = res.result.map((item: any) => {
          return {
            key: item.words,
            label: item.title,
            tooltip: item.description,
            onClick: (e: any, sessionId: string, item: any) => {
              console.log("send tip: \n", item);
              if (item.key) {
                console.log("send: " + item.key);
                sendMsg(item.key, sessionId);
                setOpenPopoverTips(false);
                setInputValue('');
              }
              // const v = e.domEvent.target.getAttribute("data-value")
              // if (v) {
                // setOpenPopoverTips(false);
              //   setInputValue(v);
              // }
            },
          }
        })
  
        setWordTips(wordTips);
      }).catch((err: any) => {
        console.log('加载提示词失败', err);
      });
    }

    const loadMcpConfigs = () => {
      getMcpConfigs().then((res: ResponseModal<ResponseMCPConfig>) => {
        if (res.code === 0 && res.success) {
          const result = res.result || [];
          setMcpConfigs([...result]);
        } else {
          message.error(res.message || "加载mcp工作流列表失败");
        }
      }).catch((err) => {
        console.log('加载mcp工作流列表失败', err);
      });
    }
  
    const findInputType = (items: MenuProps['items'],key: string) => {
      for (const item of items || []) {
        if (item?.key === key) return item;
      }
      return undefined;
    }
  
    const onTypingComplete = useCallback(() => {
      setIsTyping(false);
      setLastContentId('');
    }, []);
  
    const onResendMsgComplete = useCallback((msg: string) => {
      sendMsg(msg);
    }, [sendMsg]);
  
    const onConfirmMsgComplete = useCallback((lastMsgId: number) => {
      console.log('确认执行消息', lastMsgId);
      loadMsg(msgId.toString(), (content: any[]) => {});
    }, [loadMsg]);
  
    const onScrollToBottom = useCallback((msgContent: HTMLDivElement)=> {
      contentMsgRef.current = msgContent;
    },[]);
  
    // const handleInputTypeClick: MenuProps['onClick'] = (info) => {
    //   console.log(info);
    //   const foundItem = findInputType(inputTypes, info.key);
    //   if (foundItem && 'label' in foundItem) {
    //     setInputType(foundItem.label);
    //   }
    //   if (info.key === 'text') setInputArea(inputText);
    //   else if (info.key === 'audio') setInputArea(inputAudio);
    // }
  
    // 录音
    const startRecording = async () => {
      try {
        console.log("开始录音");
        const stream = await navigator.mediaDevices.getUserMedia({audio: true,video:false});
        mediaStreamRef.current = stream;
        mediaRecorderRef.current = new MediaRecorder(mediaStreamRef.current);
  
        mediaRecorderRef.current.ondataavailable = (event) => {
          audioChunksRef.current.push(event.data);
        }
  
        mediaRecorderRef.current.onstop = () => {
          const audioBlob = new Blob(audioChunksRef.current, {type: 'audio/wav'});
          audioChunksRef.current = [];
          console.log("开始上传录音..");
  
          // 保存录音文件
      //     const url = URL.createObjectURL(audioBlob);
      // const a = document.createElement('a');
      // a.href = url;
      // a.download = 'recording.webm'; // 默认文件名
      // document.body.appendChild(a);
      // a.click();
      // document.body.removeChild(a);
      // URL.revokeObjectURL(url);
  
          // const wavBlob = convertToWav(audioBlob);
          // let uid = randomUUID().toString();
          detectAudioFormat(audioBlob);
          const fileName = "chatAudio.wav";
          // console.log("文件名为: " + uid);
          
          chatAudio(audioBlob,fileName);
          // wavBlob.then(res => {
          //   detectAudioFormat(res);
            
          // }).catch(err => {
          //   console.log("转换失败",err);
          // });
        }
        mediaRecorderRef.current.start();
        setIsRecording(true);
      } catch(err) {
        setIsRecording(false);
        console.error("录音异常：",err);
      }
    };
  
    const stopRecording = () => {
      console.log("停止录音");
      if (mediaRecorderRef.current) {
        mediaStreamRef.current?.getTracks().forEach((track) => track.stop());
        mediaRecorderRef.current.stop();
        mediaRecorderRef.current = null;
        mediaStreamRef.current = null;
        setIsRecording(false);
      }
    };
  
   
  
    const chatAudio = async (audioBlob: Blob, fileName: string) => {
      const audioData = new FormData();
      audioData.append('file',audioBlob,fileName);
      setIsUpAudio(true);
      try {
        await post("/ai/chat/audio/upload", audioData).then(res => {
          console.log(res);
          let msg = res?.result;
          // if (res.success && res.code == 0) {
          //   sendMsg(res.result);
          // // }else if (res.success && res.code == 401) {
          // //   sendMsg(res.result);
          // }else {
          //   msg = res?.message || "无效录音";
          //   console.error(msg);
          //   message.error(msg);
          // }
          if (res.code === 0 && res.success && msg) {
            // console.log("已发送");
            // const iValue = inputValue + res.result;
            // setInputValue(iValue);
            sendMsg(res.result);
          } else {
            msg = res?.message || "无效录音";
            console.error(msg);
            message.error(msg);
          }
        }).catch(err => {
          console.error("请求失败：",err);
          message.error("请求失败!");
        }).finally(() => {
          setIsUpAudio(false);
        });
      } catch (err) {
        console.error("上传失败：",err);
        message.error("上传失败!");
        setIsUpAudio(false);
      }
    };
  
    // 录音转换wav
    const convertToWav = async (audioBlob: Blob): Promise<Blob> => {
      const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();
      const arrayBuffer = await audioBlob.arrayBuffer();
      const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
  
      const wavBlob = encodeWav(audioBuffer);
      return wavBlob;
    };
  
    const detectAudioFormat = (blob: Blob) => {
      const reader = new FileReader();
      reader.onload = (event) => {
        const arrayBuffer = event.target?.result;
        if (!arrayBuffer) return;
        
        const uint8Array = new Uint8Array(arrayBuffer as ArrayBuffer);
        const hexHeader = uint8Array.slice(0,4).reduce((acc,byte) => acc + byte.toString(16).padStart(2,'0'),'');
  
        console.log("文件头： " + hexHeader);
  
        let format: string | null = null;
        if (hexHeader.startsWith('52494646')) {
          format = 'WAV';
        } else if (hexHeader.startsWith('4f676753')) {
          format = 'OGG';
        } else if (hexHeader.startsWith('664c6143')) {
          format = 'FLAC';
        } else if (hexHeader.startsWith('fffb') || hexHeader.startsWith('fff3')) {
          format = 'MP3';
        } else if (hexHeader.startsWith('1a45dfa3')) {
          format = 'WebM';
        } else {
          format = '未知格式';
        }
        console.log('音频格式:' + format);
      };
      reader.readAsArrayBuffer(blob.slice(0,4));
    };
  
    const encodeWav = (audioBuffer: AudioBuffer):Blob => {
      const numOfChannels = audioBuffer.numberOfChannels;
      const sampleRate = audioBuffer.sampleRate;
      const length = audioBuffer.length * numOfChannels * 2 + 44;
      const buffer = new ArrayBuffer(length);
      const view = new DataView(buffer);
  
      writeStrting(view,0,'RIFF');
      view.setUint32(4,length-8,true);
      writeStrting(view,8,'WAVE');
      writeStrting(view,12,'fmt');
      view.setUint32(16,16,true);
      view.setUint16(20,1,true);
      view.setUint16(22,numOfChannels,true);
      view.setUint32(24,sampleRate,true);
      view.setUint32(28,sampleRate * numOfChannels * 2,true);
      view.setUint16(32,numOfChannels*2,true);
      view.setUint16(34,16,true);
      writeStrting(view,36,'data');
      view.setUint32(40,length - 44,true);
  
      const offset = 44;
      const interleaved = interleave(audioBuffer);
      for(let i = 0;i < interleaved.length;i++ ) {
        view.setInt16(offset + i * 2,interleaved[i] * 0x7fff,true);
      }
  
      return new Blob([buffer],{type: 'audio/wav'});
    };
  
    const writeStrting = (view: DataView,offset: number,str: string) => {
      for(let i = 0;i < str.length;i++) {
        view.setUint8(offset+i,str.charCodeAt(i));
      }
    };
  
    const interleave = (audioBuffer: AudioBuffer): Float32Array => {
      const numOfChannels = audioBuffer.numberOfChannels;
      const length = audioBuffer.length;
      const interleaved = new Float32Array(length * numOfChannels);
  
      for(let channel = 0; channel < numOfChannels;channel++) {
        const channelData = audioBuffer.getChannelData(channel);
        for(let i = 0;i < length;i++) {
          interleaved[i * numOfChannels + channel] = channelData[i];
        }
      }
      return interleaved;
    };
  
    // const startRecord = () => {
    //   startRecording();
    // };
  
    // const stopRecord = () => {
    //   stopRecording();
    // };
  
    const handleRecord = () => {
      console.log("handleRecord");
      if (isUpAudio) {
        message.warning("语音识别中");
        return;
      }
      if (isRecording) {
        stopRecording();
      } else {
        startRecording();
      }
    }
  
    // const inputTypes: MenuProps['items'] = [
    //   {
    //     key: 'text',
    //     label: (
    //       <MessageOutlined />
    //     ),
    //   },
    //   {
    //     key: 'audio',
    //     label: (
    //       <AudioOutlined />
    //     ),
    //   },
    // ];
  
    // const inputText = (
    //   <Input.TextArea
    //           // value={inputValue} // 使用 inputValue 状态作为输入框的值
    //           placeholder="给GPT提问吧"
    //           size="large"
    //           showCount={true}
    //           allowClear={true}
    //           autoSize={{ minRows: 1, maxRows: 6 }} // 自动调整行数
    //           onKeyDown={(e) => {
    //             console.log('按下键', e.key);
    //             if (e.key == 'Tab') {
    //               console.log('按下Tab键');
    //               setOpenPopoverTips(true);
    //             } else if (e.key == 'Enter' && e.shiftKey) {
    //               e.preventDefault();
    //               console.log('按下Enter键');
    //               if (inputValue) {
    //                 const value = inputValue.trim();
    //                 sendMsg(value);
    //                 setInputValue(''); // 发送消息后清空输入框
    //               }
    //             }
    //           }}
    //           onChange={(e) => {
    //             if (e.target.value == '/') {
    //               setOpenPopoverTips(true);
    //             } else {
    //               if (openPopoverTips) {
    //                 setOpenPopoverTips(false);
    //               }
    //             }
    //             setInputValue(e.target.value);
    //           }}
    //           style={{
    //             flex: 1, // 使 TextArea 占据剩余空间
    //             textAlign: 'left', // 确保文本居左对齐
    //           }}
    //         />
    // );
  
  
    // const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    //   const file = event.target.files?.[0];
    //   if (file) {
    //     // 检查是否是音频文件
    //     if (!file.type.startsWith('audio/')) {
    //       alert('请选择音频文件！');
    //       return;
    //     }
    //     chatAudio(file,file.name);
    //   }
    // }
  
    // const iconRecord = (
    //   <AudioMutedOutlined />
    // )
    // const startRecord = (
    //   <AudioTwoTone />
    // )
    // const inputAudio = (
    //   <Button style={{
    //     flex: 1,
    //   }} onMouseDown={startRecord} onMouseUp={stopRecord} loading={isRecording}>{iconRecord}</Button>
    // );
  
    // const inputUpFile = (
    //   <input type="file" accept="audio/*" onChange={handleFileChange} />
    // );
  
    // const getMsg = (inputmsg: string) => {
    //   if (openMCP) {
    //     const mcpConfigStr = mcpConfigs.map((item) => JSON.stringify(item)).join(",");
    //     const mcpMsg = `可用函数定义：${mcpConfigStr}，用户输入：${inputmsg}`;
    //     return mcpMsg;
    //   }
    //   return inputmsg;
    // }
  
    const memoizedMsgContent = useMemo(() => msgContent, [msgContent]);
  
    return (
      <>
      <Layout style={{ height: '100vh' }}>
        <Sider trigger={null} collapsible collapsed={collapsed} theme="light" collapsedWidth={100} width={250} style={{ padding: '0px', height: '100vh' }}>
          {/* <div className="demo-logo-vertical mb-5" style={{ textAlign: 'center', padding: '15px 15px 15px 15px', backgroundColor: '#1890ff', color: '#fff' }}>
            <Row>
              <Col span={3}>
                <Image src="/logo.png" alt="logo" width={30} height={30} />
              </Col>
              <Col span={12} style={{ textAlign: 'left', paddingLeft: 10 }}>
                <span className="text-lg font-bold">TSLM</span>
              </Col>
            </Row>
          </div> */}
          <div style={{ padding: 20 }}>
            <Button color="default" variant="outlined" style={{ color: "#1890ff", borderColor: "rgba(24, 144, 255, 0.1)", backgroundColor: "rgba(24, 144, 255, 0.08)", width: '100%', marginBottom: 10, height: 35, display: 'flex', justifyContent: 'flex-start', alignItems: 'center' }} onClick={() => {
              createMsg('新建对话', (id: string) => {
                setMsgId(id);
                setSelectedKey(id.toString()); // 确保转换为字符串
                loadMsg(id, (content: any[]) => {});
              });
            }}>
              <PlusOutlined />
              新对话
            </Button>
            <Menu
              mode="inline"
              selectedKeys={[selectedKey]}
              onClick={handleMsgClick}
              items={msgList}
              style={{
                maxHeight: 'calc(100vh - 200px)',
                overflowY: 'auto',
              }}
            >
            </Menu>
  
            <div className="flex justify-start items-end pb-5" style={{ position: 'absolute', bottom: 0, width: '100%' }}>
              <Space align="center">
                <Image src="/logo.png" alt="logo" width={30} height={30} />
                <div className="cursor-pointer" onClick={() => {
                  console.log('click');
                }}>
                  {/* <span className="text-sm font-bold">升级套餐</span><br /> */}
                  {/* <span className="font-bold text-lg" >钛安安全运营大模型</span> */}
                  <span className="font-bold text-lg" >{firmName}</span>
                </div>
              </Space>
            </div>
          </div>
        </Sider>
        <Layout>
          <Header style={{ padding: 0, background: "#fafafa" }}>
            <Row>
              <Col span={12}  style={{ textAlign: 'left'}}>
                {/*  绘画名称的标题 */}
                <span className="title_style font-bold ml-5">欢迎进入 TSLM{firmName}  {appInfo?.name || "我是对话名称标题"}</span>
              </Col>
              {/* <Col span={11} >
                
              </Col> */}
              <Col span={12} className="pr-5" style={{ textAlign: "right" }}>
                
              </Col>
            </Row>
          </Header>
          <Content
            style={{
              margin: '24px 16px',
              padding: 24,
              minHeight: 280,
              background: colorBgContainer,
              borderRadius: borderRadiusLG,
              textAlign: "center"
            }}
          >
            <Layout style={{ height: '100%', background: 'transparent' }}>
              <Content style={{ textAlign: 'center', display: 'flex', justifyContent: 'center' }}>
                <div style={{ height: '100%', maxWidth: 800, width: '100%' }}>
                  {
                    contentType == 'info' || msgContent.length == 0 ? <ContentInfo wordTips={wordTips.slice(0, 8)} msgId={msgId} /> : <ContentMsg msgContent={memoizedMsgContent}
                      contentId={lastContentId}
                      onUpdateMsgContent={(newContent: any) => {
                        const updatedMsgContent = msgContent.map((item: any) => {
                          const newItem = newContent.id === item.id;
                          if (newItem) {
                            if (!newContent.answer) newContent.key = '-1000';
                          }
                          return newItem ? newContent : item;
                        });
                        setMsgContent(updatedMsgContent);
                      }}
                      onTypingComplete={onTypingComplete}
                      onResendMsgComplete={onResendMsgComplete}
                      onConfirmMsgComplete={onConfirmMsgComplete}
                      onScrollToBottom={onScrollToBottom} />
                  } {/* 根据选中的菜单项渲染内容 */}
                </div>
              </Content>
              <Footer style={{ background: 'transparent' }}>
                {/* <Popover
                  placement="topLeft"
                  title="选择提示词"
                  trigger={'click'}
                  open={openPopoverTips}
                  onOpenChange={(open) => {
                    // setOpenPopoverTips(open);
                  }}
                  content={
                    <>
                      <Menu style={{ width: '90%', maxWidth: 700 }} >
                        {
                          wordTips.map((item: any, index: number) => {
                            return (
                              <Menu.Item key={`${item.key}-${index}`} onClick={item.onClick} data-value={item.key}>
                                <Tooltip title={item.label} color="">
                                  {item.label}
                                </Tooltip>
                              </Menu.Item>
                            );
                          })
                        }
                        <span className="text-gray-500 text-sm">输入"/"鼠标悬停此处以获取提示词，按Tab键进入选择区域，使用上下箭头键选择提示词</span>
                      </Menu>
                    </>
                  }
                  overlayStyle={{ width: '90%', maxWidth: 700 }}
                >
                  <div style={{ display: 'flex', justifyContent: 'center' }}>
                    <Input.Group
                      compact
                      style={{
                        display: 'flex',
                        maxWidth: 800,
                        width: '100%',
                        // borderRadius: 30, // 圆角
                        boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)', // 阴影效果
                        overflow: 'hidden' // 确保子元素不会超出圆角
                      }}
                    >
                      <Button
                        style={{
                          cursor: 'pointer',
                          backgroundColor: '#f0f0f0', // 灰色背景
                          height: 'auto', // 自适应高度
                          alignSelf: 'stretch' // 使按钮高度与 TextArea 一致
                        }}
                        onClick={() => {
                          console.log('click http');
                          return (<Button>123</Button>)
                        }}
                      >
                        <MessageOutlined />
                      </Button> */}
                      {/* <Dropdown menu={{ items: inputTypes,onClick: handleInputTypeClick, }} placement="top" trigger={['click']}>
                      <Button style={{
                                cursor: 'pointer',
                                backgroundColor: '#f0f0f0', // 灰色背景
                                height: 'auto', // 自适应高度
                                alignSelf: 'stretch' // 使按钮高度与 TextArea 一致
                              }}>{ inputType }</Button>
                      </Dropdown> */}
                      {/* <Input.TextArea
                        value={inputValue} // 使用 inputValue 状态作为输入框的值
                        placeholder="给GPT提问吧"
                        size="large"
                        showCount={true}
                        autoSize={{ minRows: 1, maxRows: 6 }} // 自动调整行数
                        onKeyDown={(e) => {
                          console.log('按下键', e.key);
                          if (e.key == 'Tab') {
                            console.log('按下Tab键');
                            setOpenPopoverTips(true);
                          } else if (e.key == 'Enter' && !e.shiftKey) {
                            e.preventDefault();
                            console.log('按下Enter键');
                            if (inputValue) {
                              const value = inputValue.trim();
                              sendMsg(value);
                              setInputValue(''); // 发送消息后清空输入框
                            }
                          }
                          // else if (e.key == 'Enter' && e.shiftKey) {
                          //   e.preventDefault();
                          //   console.log('按下Enter键');
                          //   if (inputValue) {
                          //     const value = inputValue.trim();
                          //     sendMsg(value);
                          //     setInputValue(''); // 发送消息后清空输入框
                          //   }
                          // }
                        }}
                        onChange={(e) => {
                          if (e.target.value == '/') {
                            setOpenPopoverTips(true);
                          } else {
                            if (openPopoverTips) {
                              setOpenPopoverTips(false);
                            }
                          }
                          setInputValue(e.target.value);
                        }}
                        style={{
                          flex: 1, // 使 TextArea 占据剩余空间
                          textAlign: 'left', // 确保文本居左对齐
                        }}
                      /> */}
                      {/* {inputArea} */}
                      {/* <Button style={{
                        flex: 1,
                      }}>长按开始录音</Button> */}
                      {/* <Button style={{
                          cursor: 'pointer',
                          backgroundColor: '#f0f0f0', // 灰色背景
                          height: 'auto', // 自适应高度
                          alignSelf: 'stretch', // 使按钮高度与 TextArea 一致
                          marginRight: 1,
                        }}
                        // onMouseDown={startRecord} 
                        // onMouseUp={stopRecord} 
                        onClick={handleRecord}
                        loading={isUpAudio}
                        >
                          {isRecording ? (<AudioMutedOutlined />) : (<AudioTwoTone />)}
                        </Button>
                      <Button
                        style={{
                          cursor: 'pointer',
                          backgroundColor: '#f0f0f0', // 灰色背景
                          height: 'auto', // 自适应高度
                          alignSelf: 'stretch' // 使按钮高度与 TextArea 一致
                        }}
                        onClick={() => {
                          console.log('点击');
                          if (inputValue) {
                            const value = inputValue.trim();
                            sendMsg(value);
                            setInputValue(''); // 发送消息后清空输入框
                          }
                        }}
                      >
                        <ArrowUpOutlined />
                      </Button>
                    </Input.Group>
                  </div>
                </Popover> */}
                <div className="w-full flex flex-col items-center justify-center">
                  <Popover
                    content={<>
                      <div className="w-full h-fit flex flex-row items-center justify-start py-4 px-3">
                        {
                          (qaType === QaType.WORDTIPS) && (<>
                            <div className="w-full flex flex-col items-start justify-center gap-3">
                              <div className="font-bold">选择提示词</div>
                              <div className="scrollbar-style w-full max-h-80 flex flex-col items-start justify-center gap-1 px-1 overflow-y-auto">
                                {
                                  wordTips.map((item: any, index: number) => (<>
                                    <div 
                                    key={"word_tip_" + item.key + "_" + index}
                                    className="w-full flex flex-row items-center justify-start px-4 py-2 cursor-pointer rounded-md hover:bg-gray-200"
                                    onClick={(e) => {item.onClick(e, msgId, item)}}
                                    >
                                      {item.label}
                                    </div>
                                  </>))
                                }
                              </div>
                              <div className="text-gray-500 text-sm">输入"/"鼠标悬停此处以获取提示词，按Tab键进入选择区域，使用上下箭头键选择提示词</div>
                            </div>
                            </>)
                        }
                        {
                          (qaType === QaType.MCP) && (
                            <>
                              <div className="w-full flex flex-col items-start justify-center gap-3">
                                <div className="w-full flex flex-col items-start justify-center gap-1">
                                  {
                                    mcpConfigs.map((item, index) => (<>
                                      <div className="w-full flex flex-row items-start justify-between cursor-pointer rounded-md px-3 py-2 hover:bg-gray-200">
                                        <div className="flex flex-row items-center justify-center gap-1">
                                          <div className="w-3 flex flex-row items-end justify-end text-gray-500">
                                            <ISAV1Svg width={`100%`} height={`100%`} />
                                          </div>
                                          <div className="h-full text-center flex flex-row items-center justify-center">{item.name}</div>
                                        </div>
                                        <div className="text-gray-500">{item.desc}</div>
                                      </div>
                                    </>))
                                  }
                                </div>
                                <div className="">
                                  <div className="text-gray-500 text-sm">MCP&nbsp;服务器</div>
                                </div>
                              </div>
                            </>
                          )
                        }
                      </div>
                    </>}
                    placement="top"
                    trigger={'click'}
                    open={openPopoverTips}
                    zIndex={100}
                    onOpenChange={(open) => {
                      // setOpenPopoverTips(open);
                    }}
                    overlayInnerStyle={{padding: 0, margin: 0, width: "100%"}}
                    overlayStyle={{width: "100%"}}
                    getPopupContainer={(node) => node}
                    >
                    <div className="relative max-w-4xl w-full flex flex-col items-center justify-center rounded-lg border border-[#F0F0F0] shadow-lg shadow-gray-300 py-2">
                      <div className="w-full flex flex-col items-center justify-center gap-1">
                        <div className="w-full max-h-44 min-h-0 py-2 px-4 flex flex-col items-center justify-center">
                          <textarea 
                            ref={qaTextArea}
                            value={inputValue} // 使用 inputValue 状态作为输入框的值
                            placeholder="给GPT提问吧"
                            rows={1}
                            className="scrollbar-style w-full min-h-0 border-none outline-none resize-none text-base" 
                            onClick={() => {
                              setOpenPopoverTips(false);
                            }}
                            onKeyDown={(e) => {
                              // console.log('按下键', e.key);
                              if (e.key == 'Tab') {
                                console.log('按下Tab键');
                                e.preventDefault();
                                setQaType(QaType.WORDTIPS);
                                setOpenPopoverTips(!openPopoverTips);
                              } else if (e.key == 'Enter' && !e.shiftKey) {
                                e.preventDefault();
                                console.log('按下Enter键');
                                if (inputValue) {
                                  const value = inputValue.trim();
                                  // const chatMsg = getMsg(value);
                                  UtilHelpers.CleanTimeout("Process-msg");
                                  sendMsg(value);
                                  setInputValue(''); // 发送消息后清空输入框
                                }
                              }
                              // else if (e.key == 'Enter' && e.shiftKey) {
                              //   e.preventDefault();
                              //   console.log('按下Enter键');
                              //   if (inputValue) {
                              //     const value = inputValue.trim();
                              //     sendMsg(value);
                              //     setInputValue(''); // 发送消息后清空输入框
                              //   }
                              // }
                            }}
                            onChange={(e) => {
                              if (e.target.value == '/') {
                                setQaType(QaType.WORDTIPS);
                                setOpenPopoverTips(true);
                              } else {
                                if (openPopoverTips) {
                                  setOpenPopoverTips(false);
                                }
                              }
                              setInputValue(e.target.value);
                            }}
                          />
                        </div>
                      </div>
                      <div className="w-full flex flex-row items-center justify-between gap-1 px-2">
                        <div className="h-full flex flex-row items-center justify-center gap-1">
                          <div 
                          className={`w-9 flex flex-row items-center justify-center p-2 cursor-pointer rounded-md hover:bg-gray-200 ${openMCP ? "text-blue-500": "text-gray-600"}`}
                          onClick={() => {
                            setOpenMCP(openMCP => {
                              if (!openMCP) {
                                setQaType(QaType.MCP);
                              }
                              setOpenPopoverTips(!openMCP);
                              return !openMCP;
                            });

                          }}
                          onMouseEnter={() => {
                            if (openMCP) {
                              setQaType(QaType.MCP);
                              setOpenPopoverTips(true);
                            }
                          }}
                          >
                            <MaintenanceSvg width={"100%"} height={"100%"} />
                          </div>
                          <div className="text-red-500">{openMCP ? "mcp已开启":""}</div>
                        </div>
                        <div className="h-full flex flex-row items-center justify-center gap-1">
                          <div 
                          className="p-2 h-full flex flex-row items-center justify-center cursor-pointer"
                          onClick={handleRecord}
                          >
                            <div className={`${isUpAudio ? "": "hidden"} w-4 animate-spin`}>
                              <LoadingSvg width={"100%"} height={"100%"} />
                            </div>
                            <div className="flex flex-row items-center justify-center">
                            {isRecording ? (<AudioMutedOutlined />) : (<AudioTwoTone />)}
                            </div>
                          </div>
                          <div 
                          className={`p-2 h-full flex flex-row items-center justify-center rounded-full text-white ${inputValue.length > 0 ? "bg-blue-500 cursor-pointer":"bg-gray-300 cursor-not-allowed"}`}
                          onClick={() => {
                            console.log('点击');
                            if (inputValue) {
                              const value = inputValue.trim();
                              UtilHelpers.CleanTimeout("Process-msg");
                              sendMsg(value);
                              setInputValue(''); // 发送消息后清空输入框
                            }
                          }}
                          >
                            <ArrowUpOutlined />
                          </div>  
                        </div>
                      </div>
                    </div>
                  </Popover>
                </div>
              </Footer>
            </Layout>
          </Content>
          <ShowDialog open={dialogOpen} setOpen={setDialogOpen} />
          <CueWordManage open={cueWordMaintenance} setOpen={setCueWordMaintenance}/>
        </Layout>
      </Layout>
      </>
    );
}
// export default NewPage;